package com.rw.coco.handler.message.reply.handler.command;

import com.rw.coco.api.reply.mapper.DiceReply;
import com.rw.coco.handler.message.event.CocoMessageEvent;
import com.rw.coco.handler.message.reply.ReplyHandler;
import com.rw.coco.handler.message.reply.handler.command.assistant.CommandMatcher;
import com.rw.coco.handler.message.reply.handler.command.exception.ra.PropNotFoundException;
import com.rw.coco.handler.message.reply.handler.command.sender.SCSender;
import com.rw.coco.util.config.CocoCommandConfig;
import com.rw.coco.util.config.CocoConfig;
import com.rw.coco.util.config.CocoOption;

/**
 * 理智鉴定
 * .sc
 */
public class SCHandler implements ReplyHandler {
    private final CommandMatcher matcher;

    public final boolean funcSwitch;

    public SCHandler(CocoConfig cocoConfig) {
        CocoCommandConfig cocoCommandConfig = cocoConfig.getCocoCommandConfig();
        CocoOption cocoOption = cocoConfig.getCocoOption();

        String command = cocoCommandConfig.commandProp.get(CocoCommandConfig.SC);
        this.matcher = CommandMatcher.of(command);
        this.funcSwitch = cocoOption.optionProp.getBoolean(CocoOption.COCO_SC);
    }

    @Override
    public boolean trigger(CocoMessageEvent cocoMessageEvent) {
        String message = cocoMessageEvent.getMessage();
        return funcSwitch && matcher.isMatch(message);
    }

    @Override
    public void handler(CocoMessageEvent cocoMessageEvent) {
        // 去掉sc前缀
        String scCommand = matcher.subTrim(cocoMessageEvent.getMessage());
        String[] commandArr = scCommand.split("/");
        DiceReply diceReply = cocoMessageEvent.getReplyApi().getDiceReply();

        // 指令必须是由 '/' 号分开的两部分
        if (commandArr.length != 2) {
            cocoMessageEvent.sendBack(diceReply.scParseError(cocoMessageEvent, scCommand));
            return;
        }

        // 使用解析出的两个指令，构造sender
        String successExpression = commandArr[0];
        String failExpression = commandArr[1];
        SCSender sender = new SCSender(successExpression, failExpression, cocoMessageEvent);

        // 操作san值，并且返回消息
        try {
            sender.check();
        } catch (PropNotFoundException exception) {
            // 在角色属性中，没有找到对应的san值
            // TODO 制作完未完成的SC指令
        }
    }

    @Override
    public int priority() {
        return matcher.priority();
    }
}